Grokking SQL for Tech Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Course Overview
What is RDBMS?
What is SQL?
A Quick Review of SQL
Read data from table
WHERE Clause
Operators
Handle NULLs in SQL
DISTINCT Clause
ORDER BY Clause
LIMIT and OFFSET
GROUP BY
HAVING
Aggregate Functions
Order of Execution
Order of SQL Query Execution
SQL Functions
Number Functions
String Functions
Date Functions
Nested Query
Types of Subqueries
Introduction
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
SELF JOIN
What are SET operations?
UNION
INTERSECT
EXCEPT
Keys in SQL
CREATE
ALTER
DROP
TRUNCATE
Indexes
INSERT
UPDATE
DELETE
Backup Database
Restore Database
1. Major Cities
2. Not boring movies
3. Triangle Judgement
4. Biggest Single Number
5. Product Sales Analysis I
6. Product Sales Analysis II
7. Game Play Analysis I
8. Game Play Analysis II
9. Queries Quality and Percentage
10. Average Selling Price
11. Weather Type in Each Country
12. Students and Examinations
13. Ads Performance
14. Group Sold Products By The Date
15. Employee Email Verification
16. Sellers With No Sales
17. Average Time of Process
18. Find Followers Count
19. Ad-Free Sessions
20. Bikes Last Time Used
21. Daily User Engagement Levels
22. Employee Attendance Record
23. Library Book Loans
24. Customer Purchase Summary
25. Long Comments (Easy)
26. Unused Accounts
27. Patient Appointment No-Shows
28. Books and Authors
29. High School Attendance
30. Employee Absences
31. Green Product Identification (Easy)
32. Employee Department Exclusion (Easy)
33. Sales Person (Easy)
34. Employee Task Tracking (Easy)
1. Winning Candidate
2. Second Degree Follower
3. 2nd Highest Salary
4. Game Play Analysis III
5. Game Play Analysis IV
6. Active Businesses
7. Product Price on a Specific Date
8. Monthly Transactions II
9. Team Scores in Football Tournament
10. Page Recommendations
11. Running Total for Different Genders
12. Evaluate Boolean Expression
13. Active Users
14. Find Interview Candidates
15. Suspicious Bank Accounts
16. Order Fulfillment Rate (Medium)
17. Last Person to Fit in the Elevator (Medium)
18. Retail Expansion Analysis (Medium)
19. Employee Collaboration Networks (Medium)
20. Second Fastest Time in Races (Medium)
1. Trips and Users
2. Human Traffic of Stadium
3. Students Report By Geography
4. Game Play Analysis V
5. Number of Transactions per Visit
6. Find the Quiet Students in All Exams
7. First and Last Call On the Same Day
8. Build the Equation
9. Longest Winning Streak
10. Dynamic Pivoting of a Table
11. Dynamic Unpivoting of a Table
12. Generate the Invoice
13. Popularity Percentage
14. Viewers Turned Streamers
15. Status of Flight Tickets
1. High Performing Employees (Easy)
2. Student Course Averages (Easy)
3. Library Book Checkout Percentage (Easy)
4. Employee Performance and Improvement Rate (Easy)
5. Find Popular Posts (Easy)
6. Main Office Assignment for Each Employee (Easy)
7. Rectangle Validation (Easy)
8. Library Book Checkouts by Date (Easy)
9. Same-Day Appointment Fulfillment (Medium)
10. Departments with High Earning Employees (Medium)
11. Students Who Attended All Courses (Medium)
12. Library Book Checkouts First Year (Medium)
13. Repeated Values in Sequence (Medium)
14. School Top Achievers by Subject (Hard)
Number Functions

One of the standout features that amplify SQL's prowess is its extensive suite of built-in numeric functions. These functions serve as powerful tools, enabling users to perform a wide range of operations—from simple calculations to intricate data manipulations. By leveraging these functions, you can streamline your queries, enhance efficiency, and extract meaningful insights from even the most complex datasets.

Why Numeric Functions Matter

Numeric functions in SQL simplify complex mathematical operations, making your queries more concise and readable. Whether you're rounding numbers, calculating averages, or performing exponential calculations, these functions enhance the precision and effectiveness of your data analysis.

Key Numeric Functions in SQL

Let's dive into some of the most essential numeric functions in SQL, complete with descriptions and practical examples to illustrate their usage.

1. ABS()

The ABS() function returns the absolute value of a number, effectively converting negative numbers to positive ones. This is particularly useful when you need to ensure that values are non-negative, such as calculating distances or differences.

Example:

SELECT ABS(-10) AS AbsoluteValue; -- Result: 10

2. ROUND()

The ROUND() function rounds a numeric field to the specified number of decimal places. It's ideal for presenting data in a more readable format by trimming unnecessary decimal places.

Example:

SELECT ROUND(9.876, 1) AS RoundedNumber; -- Result: 9.9

3. CEIL()andFLOOR()

  • CEIL(): Rounds a number up to the nearest integer.
  • FLOOR(): Rounds a number down to the nearest integer.

These functions are essential when you need to control the direction of rounding, such as allocating resources or setting thresholds.

Example:

SELECT CEIL(4.3) AS Ceiling, FLOOR(4.8) AS Floor; -- Results: 5, 4

4. SQRT()

The SQRT() function calculates the square root of a given number. It's useful in various mathematical computations, including statistical analyses and geometric calculations.

Example:

SELECT SQRT(25) AS SquareRoot; -- Result: 5

5. POWER()

The POWER() function raises a number to the specified power, enabling exponential calculations. This is beneficial for growth projections, financial calculations, and scientific data analysis.

Example:

SELECT POWER(2, 3) AS ExponentialResult; -- Result: 8

6. MOD()

The MOD() function returns the remainder of a division operation. It's commonly used to determine divisibility, cycle through sequences, or implement conditional logic based on remainders.

Example:

SELECT MOD(17, 5) AS Remainder; -- Result: 2

SQL Numeric Functions

To provide a clearer overview, here's a detailed table outlining various numeric functions in SQL, complete with descriptions and example queries:

Sr    FunctionDescriptionQueryResult
1ABS()Returns the absolute (non-negative) value of a number.SELECT ABS(-10) AS AbsoluteValue;10
2ROUND()Rounds a number to a specified number of decimal places.SELECT ROUND(9.876, 1) AS RoundedNumber;9.9
3CEIL()Rounds a number up to the nearest integer.SELECT CEIL(4.3) AS Ceiling;5
4FLOOR()Rounds a number down to the nearest integer.SELECT FLOOR(4.8) AS Floor;4
5SQRT()Calculates the square root of a number.SELECT SQRT(25) AS SquareRoot;5
6POWER()Raises a number to the power of another number.SELECT POWER(2, 3) AS ExponentialResult;8
7MOD()Returns the remainder of a division operation.SELECT MOD(17, 5) AS Remainder;`2
8RAND()Generates a random floating-point number between 0 and 1.SELECT RAND() AS RandomNumber;Random decimal number (e.g., 0.8473)
9TRUNCATE()Truncates a number to a specified number of decimal places.SELECT TRUNCATE(9.876, 1) AS Truncated;`9.8
10EXP()Returns e raised to the specified power.SELECT EXP(2) AS ExponentialValue;Approximately 7.39
11LOG()Returns the natural logarithm (base e) of a number.SELECT LOG(10) AS NaturalLog;Approximately 2.302585
12LOG10()Returns the base-10 logarithm of a number.SELECT LOG10(100) AS LogBase10;2
13SIGN()Returns the sign of a number: -1 for negative, 0 for zero, 1 for positive.SELECT SIGN(-15) AS NumberSign;-1 (negative number)
14PI()Returns the value of π (pi).SELECT PI() AS PiValue;3.141592653589793
15DEGREES()Converts radians to degrees.SELECT DEGREES(1.047) AS Degrees;Approximately 60 degrees
16RADIANS()Converts degrees to radians.SELECT RADIANS(60) AS Radians;Approximately 1.047 radians
17FORMAT()Formats a number to a specified number of decimal places, including commas.SELECT FORMAT(1234567, 2) AS FormattedNumber;1,234,567.00
18CONVERT()Converts a number to a different data type with specified precision.SELECT CONVERT(100, DECIMAL(5,2)) AS ConvertedNumber;100.00

Learning with Interactive Exercises

To solidify understanding, incorporate interactive exercises and real-world projects where students can apply these numeric functions. For example:

  • Exercise 1: Create a query that calculates the total sales, rounds the result to two decimal places, and formats it with commas for readability.

    SELECT FORMAT(ROUND(SUM(sales_amount), 2), 2) AS TotalSales FROM sales;
  • Exercise 2: Develop a report that shows the square root of the total number of products sold and the natural logarithm of total revenue.

    SELECT SQRT(COUNT(product_id)) AS ProductSqrt, LOG(SUM(revenue)) AS RevenueLog FROM sales;
Order of SQL Query Execution
String Functions
Mark as Completed

On this page

Why Numeric Functions Matter

Key Numeric Functions in SQL

  1. ABS()
  1. ROUND()
  1. CEIL()andFLOOR()
  1. SQRT()
  1. POWER()
  1. MOD()

SQL Numeric Functions

Learning with Interactive Exercises